/* Update: I'm questioning if such a program should be a part of SDTP since it is
		   not immediatly an application of data security. However, being able to
           access free information with randomization (disgusing which article was
           requested) can be important, though consumer harddrives typically support
           storing the enitre wikipedia with compressed images for multiple languages
*/

/*	TODO:

	- Add sleep-command to each wget-request
	- Let the script sleep an arbitrary time from 50 - 1500 ms
	- Tell wget to use different user agent (for instance, the one of Firefox)

*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <gcrypt.h>

#define REQ_NUM 15	// Number of requests

int main()
{
	char xbuffer[128], ybuffer[128];
	char ** list;
	FILE * f;
	FILE * out;
	register char c;
	register unsigned int i, j, k;
	register unsigned int line_len = 0;
	uint32_t lines = 0;
	uint32_t article_rand;
	uint8_t n_real;

	gcry_randomize(&n_real, 1, GCRY_VERY_STRONG_RANDOM);

	n_real %= REQ_NUM;	// Number of requests
	// Is this biased? Check! TODO

	f = fopen("dewiki-latest-all-titles-in-ns0", "r");

	do {
		c = fgetc(f);
		if (c == '\n')
			lines++;
	} while (c != EOF);

	if (c != '\n' && lines != 0)
		lines++;

	rewind(f);

	list = malloc(lines * sizeof(char*));

	i = 0;

	while (fgets(xbuffer, 128, f) != NULL)
	{
		list[i] = malloc(strlen(xbuffer) + 1);
		strlcpy(list[i], xbuffer, strlen(xbuffer));
		i++;
	}

	fclose(f);

	printf("%i articles read.\n", lines, n_real);
	printf("Search term: ");
	fgets(xbuffer, 128, stdin);
	strtok(xbuffer, "\n");

	j = 0;
	k = 0;

	for (i = 0; i < lines; i++)
	{
		if (strstr(list[i], xbuffer) != NULL)
		{
			printf("(%i) %s\n", j, list[i]);
			j++;
		}
	}

	printf("Enter article ID: ");
	fgets(ybuffer, 128, stdin);
	strtok(ybuffer, "\n");

	j = atoi(ybuffer) + 1;
	i = 0;

	do
	{
		if (strstr(list[i], xbuffer) != NULL)
			k++;

		i++;
	} while (k != j);

	strlcpy(xbuffer, list[i-1], 128);

	out = fopen("get_wiki", "w");

	// TODO Wait arbitrary number of milliseconds between each article

	for (i = 0; i < REQ_NUM; i++)
	{
		gcry_randomize(&article_rand, 4, GCRY_VERY_STRONG_RANDOM);
		article_rand %= lines;
		if (i != n_real)
			fprintf(out, "wget \"https://de.wikipedia.org/wiki/%s\"\n", list[article_rand]);
		else
			fprintf(out, "wget \"https://de.wikipedia.org/wiki/%s\"\n", xbuffer);
	}

	for (i = 0; i < lines; i++)
		free(list[i]);

	free(list);
	fclose(out);
}
